package cn.schoolwow.quickdao.module.database.dml.instance.flow.common.filter;

import cn.schoolwow.quickdao.domain.QuickDAOConfig;
import cn.schoolwow.quickdao.domain.database.dml.CheckStrategy;
import cn.schoolwow.quickdao.domain.entity.Entity;
import cn.schoolwow.quickdao.domain.entity.Property;
import cn.schoolwow.quickdao.module.database.dml.common.domain.ManipulationOption;
import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;
import cn.schoolwow.util.domain.query.instance.QueryInstance;

import java.util.*;

public class FilterInstanceBySameUniqueKeyFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        shouldCheck(flowContext);
        filterInstanceBySameUniqueKey(flowContext);
    }

    @Override
    public String name() {
        return "过滤唯一约束值相同的实例";
    }

    private void shouldCheck(FlowContext flowContext){
        QuickDAOConfig quickDAOConfig = flowContext.checkInstanceData(QuickDAOConfig.class);
        ManipulationOption manipulationOption = flowContext.checkInstanceData(ManipulationOption.class);
        CheckStrategy checkStrategy = null!=manipulationOption.checkStrategy?manipulationOption.checkStrategy:quickDAOConfig.databaseOption.checkStrategy;
        if(CheckStrategy.None.equals(checkStrategy)){
            flowContext.brokenCurrentFlow("根据字段约束策略,跳过过滤唯一约束值相同的实例");
        }
        Entity entity = (Entity) flowContext.checkData("entity");
        if(entity.uniqueProperties.isEmpty()){
            flowContext.brokenCurrentFlow("实例无唯一约束字段,跳过过滤唯一约束值相同的实例");
        }
    }

    private void filterInstanceBySameUniqueKey(FlowContext flowContext){
        Entity entity = (Entity) flowContext.checkData("entity");
        Object[] instances = (Object[]) flowContext.checkData("instances");
        Map<Object,String> instanceReasonMap = (Map<Object, String>) flowContext.getData("instanceReasonMap", new LinkedHashMap<String,Object>());

        Set<String> uniqueKeyValueSet = new HashSet<>();
        StringBuilder uniqueKeyValueBuilder = new StringBuilder();
        List<Object> objectList = new ArrayList<>(Arrays.asList(instances));
        Iterator<Object> iterator = objectList.iterator();
        while(iterator.hasNext()){
            Object instance = iterator.next();
            uniqueKeyValueBuilder.setLength(0);
            for(Property uniqueFieldProperty:entity.uniqueProperties){
                Object value = QueryInstance.newQuery(instance)
                        .execute()
                        .getSingleFieldValue(uniqueFieldProperty.name);
                uniqueKeyValueBuilder.append(value+"|");
            }
            String uniqueKeyValue = uniqueKeyValueBuilder.toString();
            if(uniqueKeyValueSet.contains(uniqueKeyValue)){
                String reason = "存在相同唯一约束实例!唯一约束:"+uniqueKeyValue;
                if(!instanceReasonMap.containsKey(instance)){
                    instanceReasonMap.put(instance, reason);
                }else{
                    String oldReason = instanceReasonMap.get(instance);
                    instanceReasonMap.put(instance, oldReason+";"+reason);
                }
                iterator.remove();
                continue;
            }
            uniqueKeyValueSet.add(uniqueKeyValue);
        }
        if(objectList.isEmpty()){
            flowContext.putData("effect", 0);
            flowContext.broken("根据唯一约束过滤数据后实例列表为空");
        }
        flowContext.putTemporaryData("instances", objectList.toArray(new Object[0]));
    }
}
